import dayjs from "dayjs";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import {
  getNewsList,
  createNews,
  updateNews,
  deleteNews,
  updateNewsStatus,
  batchDeleteNews,
  publishNews,
  withdrawNews,
  topNews,
  recommendNews
} from "@/api/news";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw, watch } from "vue";
import type { FormItemProps } from "../utils/types";
import {
  NewsStatus,
  NewsStatusText,
  newsStatusOptions,
  newsCategoryOptions,
  newsTagOptions,
  newsSourceOptions,
  getCategoryName,
  getStatusTagType
} from "../utils/types";
import { useNewsHook } from "../hooks";

export function useNews() {
  const form = reactive({
    title: "",
    categoryId: null,
    status: null,
    author: "",
    source: "",
    isTop: null,
    isRecommend: null,
    createTime: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle, tagStyle, getStatusTagType, getPriorityTagType, getPriorityText } = useNewsHook();
  const { tagStyle: publicTagStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列",
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号")
    },
    {
      label: "资讯标题",
      prop: "title",
      minWidth: 200,
      cellRenderer: ({ row, props }) => (
        <el-link
          class="no-pager"
          size={props.size}
          type="primary"
          underline={false}
          style={{
            fontSize: props.size === "small" ? "12px" : "14px",
            marginRight: "4px"
          }}
          onClick={() => openDialog("查看", row)}
        >
          {row.title}
        </el-link>
      )
    },
    {
      label: "分类",
      prop: "categoryId",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag size="small" type="">
          {getCategoryName(row.categoryId)}
        </el-tag>
      )
    },
    {
      label: "标签",
      prop: "tags",
      minWidth: 120,
      cellRenderer: ({ row }) => (
        <div class="flex flex-wrap gap-1">
          {row.tags?.map((tag: string, index: number) => (
            <el-tag key={index} size="small" type="info">
              {tag}
            </el-tag>
          ))}
        </div>
      )
    },
    {
      label: "作者",
      prop: "author",
      minWidth: 100
    },
    {
      label: "来源",
      prop: "source",
      minWidth: 100
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size === "small" ? "small" : "default"}
          type={getStatusTagType(row.status)}
          style={tagStyle.value(row.status)}
        >
          {NewsStatusText[row.status]}
        </el-tag>
      )
    },
    {
      label: "优先级",
      prop: "priority",
      minWidth: 100,
      cellRenderer: ({ row, props }) => {
        const priorityText = getPriorityText(row.isTop, row.isRecommend);
        const priorityType = getPriorityTagType(row.isTop, row.isRecommend);
        return priorityText ? (
          <el-tag
            size={props.size === "small" ? "small" : "default"}
            type={priorityType}
          >
            {priorityText}
          </el-tag>
        ) : (
          <span>普通</span>
        );
      }
    },
    {
      label: "阅读量",
      prop: "viewCount",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <span>{row.viewCount || 0}</span>
      )
    },
    {
      label: "点赞数",
      prop: "likeCount",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <span>{row.likeCount || 0}</span>
      )
    },
    {
      label: "评论数",
      prop: "commentCount",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <span>{row.commentCount || 0}</span>
      )
    },
    {
      label: "发布时间",
      prop: "publishTime",
      minWidth: 180,
      formatter: ({ publishTime }) =>
        dayjs(publishTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 180,
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  const buttonClass = [
    "!h-[20px]",
    "reset-margin",
    "!text-gray-500",
    "dark:!text-white",
    "dark:hover:!text-primary"
  ];

  // 生成模拟数据
  function generateMockData(count: number = 20): FormItemProps[] {
    const mockData: FormItemProps[] = [];
    const titles = [
      "2024年乒乓球世界杯即将开赛",
      "国乒队员备战巴黎奥运会最新动态",
      "乒乓球技术教学：正手攻球要领",
      "新款乒乓球拍评测报告",
      "全国青少年乒乓球锦标赛圆满落幕",
      "乒乓球运动对青少年身心发展的益处",
      "世界乒乓球排名最新更新",
      "乒乓球俱乐部联赛精彩回顾"
    ];
    const authors = ["张三", "李四", "王五", "赵六", "钱七", "孙八"];
    const sources = ["原创", "新华网", "人民网", "央视网", "中国体育报", "乒乓世界"];
    const tags = [["热门", "推荐"], ["精选"], ["教学", "技巧"], ["装备"], ["赛事"], ["原创"]];

    for (let i = 0; i < count; i++) {
      const randomTitle = titles[Math.floor(Math.random() * titles.length)];
      const randomAuthor = authors[Math.floor(Math.random() * authors.length)];
      const randomSource = sources[Math.floor(Math.random() * sources.length)];
      const randomTags = tags[Math.floor(Math.random() * tags.length)];
      const randomStatus = Math.floor(Math.random() * 3);
      const randomCategory = Math.floor(Math.random() * 6) + 1;
      const isTop = Math.random() > 0.8;
      const isRecommend = Math.random() > 0.7;
      
      mockData.push({
        id: i + 1,
        title: `${randomTitle} ${i + 1}`,
        categoryId: randomCategory,
        tags: randomTags,
        coverImage: `https://picsum.photos/400/300?random=${i}`,
        summary: `这是第${i + 1}条资讯的摘要内容，介绍了相关的乒乓球资讯信息。`,
        content: `这是第${i + 1}条资讯的详细内容，包含了丰富的乒乓球相关信息和详细描述。`,
        author: randomAuthor,
        source: randomSource,
        status: randomStatus,
        isTop,
        isRecommend,
        sort: Math.floor(Math.random() * 100),
        viewCount: Math.floor(Math.random() * 10000),
        likeCount: Math.floor(Math.random() * 1000),
        commentCount: Math.floor(Math.random() * 500),
        publishTime: dayjs().subtract(Math.floor(Math.random() * 30), "day").format("YYYY-MM-DD HH:mm:ss"),
        createTime: dayjs().subtract(Math.floor(Math.random() * 60), "day").format("YYYY-MM-DD HH:mm:ss"),
        updateTime: dayjs().subtract(Math.floor(Math.random() * 10), "day").format("YYYY-MM-DD HH:mm:ss"),
        remark: `备注信息${i + 1}`
      });
    }
    return mockData;
  }

  function handleDelete(row) {
    ElMessageBox.confirm(
      `确认要删除资讯"${row.title}"吗？`,
      "删除确认",
      {
        type: "warning"
      }
    )
      .then(async () => {
        await deleteNews(row.id);
        message("删除成功", { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  function handleBatchDelete(val) {
    if (val.length === 0) {
      message("请选择要删除的数据", { type: "warning" });
      return;
    }
    ElMessageBox.confirm(
      `确认要删除选中的 ${val.length} 条资讯吗？`,
      "批量删除确认",
      {
        type: "warning"
      }
    )
      .then(async () => {
        const ids = val.map(item => item.id);
        await batchDeleteNews(ids);
        message("批量删除成功", { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    try {
      // 模拟API调用
      const mockData = generateMockData(50);
      
      // 模拟搜索过滤
      let filteredData = mockData;
      if (form.title) {
        filteredData = filteredData.filter(item => 
          item.title.toLowerCase().includes(form.title.toLowerCase())
        );
      }
      if (form.categoryId !== null && form.categoryId !== "") {
        filteredData = filteredData.filter(item => item.categoryId === form.categoryId);
      }
      if (form.status !== null && form.status !== "") {
        filteredData = filteredData.filter(item => item.status === form.status);
      }
      if (form.author) {
        filteredData = filteredData.filter(item => 
          item.author?.toLowerCase().includes(form.author.toLowerCase())
        );
      }
      if (form.source) {
        filteredData = filteredData.filter(item => 
          item.source?.toLowerCase().includes(form.source.toLowerCase())
        );
      }
      if (form.isTop !== null && form.isTop !== "") {
        filteredData = filteredData.filter(item => item.isTop === form.isTop);
      }
      if (form.isRecommend !== null && form.isRecommend !== "") {
        filteredData = filteredData.filter(item => item.isRecommend === form.isRecommend);
      }
      
      // 模拟分页
      const total = filteredData.length;
      const start = (pagination.currentPage - 1) * pagination.pageSize;
      const end = start + pagination.pageSize;
      const pageData = filteredData.slice(start, end);
      
      dataList.value = pageData;
      pagination.total = total;
    } catch (error) {
      console.error("获取资讯列表失败:", error);
      message("获取资讯列表失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}资讯`,
      props: {
        formInline: {
          id: row?.id ?? null,
          title: row?.title ?? "",
          categoryId: row?.categoryId ?? 1,
          tags: row?.tags ?? [],
          coverImage: row?.coverImage ?? "",
          summary: row?.summary ?? "",
          content: row?.content ?? "",
          author: row?.author ?? "",
          source: row?.source ?? "原创",
          status: row?.status ?? NewsStatus.DRAFT,
          isTop: row?.isTop ?? false,
          isRecommend: row?.isRecommend ?? false,
          sort: row?.sort ?? 0,
          publishTime: row?.publishTime ?? "",
          remark: row?.remark ?? ""
        }
      },
      width: "80%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了资讯标题为${curData.title}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 实际开发中这里会调用新增或编辑接口
            if (title === "新增") {
              // createNews(curData).then(() => {
              //   chores();
              // });
              chores();
            } else {
              // updateNews(curData).then(() => {
              //   chores();
              // });
              chores();
            }
          }
        });
      }
    });
  }

  // 发布资讯
  function handlePublish(row) {
    ElMessageBox.confirm(
      `确认要发布资讯"${row.title}"吗？`,
      "发布确认",
      {
        type: "warning"
      }
    )
      .then(async () => {
        await publishNews(row.id);
        message("发布成功", { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  // 撤回资讯
  function handleWithdraw(row) {
    ElMessageBox.confirm(
      `确认要撤回资讯"${row.title}"吗？`,
      "撤回确认",
      {
        type: "warning"
      }
    )
      .then(async () => {
        await withdrawNews(row.id);
        message("撤回成功", { type: "success" });
        onSearch();
      })
      .catch(() => {});
  }

  // 置顶切换
  function handleTopChange(val: boolean, row: any) {
    ElMessageBox.confirm(
      `确认要${val ? "置顶" : "取消置顶"}资讯"${row.title}"吗？`,
      "置顶确认",
      {
        type: "warning"
      }
    )
      .then(async () => {
        switchLoadMap.value[row.id] = Object.assign(
          {},
          switchLoadMap.value[row.id],
          {
            top: true
          }
        );
        await topNews({ id: row.id, isTop: val });
        switchLoadMap.value[row.id] = Object.assign(
          {},
          switchLoadMap.value[row.id],
          {
            top: false
          }
        );
        message(`${val ? "置顶" : "取消置顶"}成功`, { type: "success" });
        onSearch();
      })
      .catch(() => {
        row.isTop = !val;
      });
  }

  // 推荐切换
  function handleRecommendChange(val: boolean, row: any) {
    ElMessageBox.confirm(
      `确认要${val ? "推荐" : "取消推荐"}资讯"${row.title}"吗？`,
      "推荐确认",
      {
        type: "warning"
      }
    )
      .then(async () => {
        switchLoadMap.value[row.id] = Object.assign(
          {},
          switchLoadMap.value[row.id],
          {
            recommend: true
          }
        );
        await recommendNews({ id: row.id, isRecommend: val });
        switchLoadMap.value[row.id] = Object.assign(
          {},
          switchLoadMap.value[row.id],
          {
            recommend: false
          }
        );
        message(`${val ? "推荐" : "取消推荐"}成功`, { type: "success" });
        onSearch();
      })
      .catch(() => {
        row.isRecommend = !val;
      });
  }

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    newsStatusOptions,
    newsCategoryOptions,
    newsTagOptions,
    newsSourceOptions,
    switchLoadMap,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    handleBatchDelete,
    handlePublish,
    handleWithdraw,
    handleTopChange,
    handleRecommendChange,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}